package com.example.texted.introspect;

import org.springframework.util.StopWatch;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.time.LocalDateTime;
import java.util.HashMap;

public class MapToBeanUtils {
    public static void main(String[] args) throws Exception {
        final HashMap<String, Object> map = new HashMap<>();
        map.put("age", "8");
        map.put("name", "李四");
        map.put("createTime", LocalDateTime.now().toString());
//        String beanPath = "com.example.texted.introspect.User";
        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        final User instance = mapToBean(map, User.class);
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
        System.out.println(instance);
    }

    private static <T> T mapToBean(HashMap<String, Object> map, Class<T> clazz) throws Exception {
        final T instance = clazz.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            final String descriptorName = descriptor.getName();
            if (map.containsKey(descriptorName)) {
                Object value = map.get(descriptorName);
                final Class<?> propertyType = descriptor.getPropertyType();
                if (propertyType.equals(LocalDateTime.class)) {
                    value = LocalDateTime.parse(value.toString());
                }
                if (propertyType.equals(Integer.class)) {
                    value = Integer.valueOf(value.toString());
                }
                descriptor.getWriteMethod().invoke(instance, value);
            }
        }
        return instance;
    }
}
